/*
 *  Copyright (C) 2011  Clint Priest
 *
 *  This file is part of pklib.
 *
 *  pklib is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  pklib is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with pklib.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

var ValueFormat = Class.create( {
	Type: 		'Number',
	Precision: 	0,
	
	DateTransforms: [
		[ /^(\d+)\/(\d+)$/, 		'YYYY-$1-$2', 	'%m/%d' ],
		[ /^(\d+)\/(\d+)\/(\d+)$/, 	'$3-$1-$2',		'%m/%d/%Y'	],
	],
	
	DateFormat: '',
	
	initialize: function(example) {
		example = String(example);
		this.Type = 'Number',
		this.Precision = example.replace(/[^\.]+\.?(.{0,})$/, '$1').length;
		
		if(example.indexOf('$') != -1) {
			this.Type = 'Dollar';
			this.Precision = 2;
		} else if (example.indexOf('%') != -1)
			this.Type = 'Percent';
		else if( example.indexOf('/') != -1) {
			this.DateTransforms.some( function( trans ) {
				var m = example.match( trans[0] );
				if(m != null) {
					this.Type = 'Date';
					this.Transform = trans;
					this.DateFormat = trans[2];
					return true;
				}
			}, this);
		}
	},
	NumericValue: function(text) {
		if( ['Number','Dollar','Percent'].indexOf(this.Type) != -1 )
			return String(text).replace(/[^\d\-\.]+/g, '');
		if(this.Type == 'Date') {
			return (new Date(
						String(text).replace(this.Transform[0], this.Transform[1])
						.replace('YYYY', (new Date()).getFullYear())
					))
					.getTime() + (new Date().getTimezoneOffset() * 60000)
		}
		return String(text);
	},
	Format: function(text) {
		if(this.Type == 'Date')
			return (new Date(text)).toLocaleFormat(this.DateFormat);
		var val = parseFloat(text);
		var out = Math.floor(val).toLocaleString();
		if(this.Precision > 0) {
			var fixed = parseFloat(val - Math.floor(val)).toFixed(this.Precision);
			out = String(fixed).replace(/^0/, out);
		}
		switch(this.Type) {
			case 'Dollar':	return '$'+out;
			case 'Percent':	return out+'%';
		}
		return out;
	}
} );
